/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package youhuizi;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.Schedule;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

/**
 *
 * @author Steven
 */
@Stateless
public class timerBean implements timerBeanRemote {
    @Resource(name = "jms/postbox")
    private Queue postbox;
    @Resource(name = "jms/postboxFactory")
    private ConnectionFactory postboxFactory;

    public int t = 0;
    public String s = new String();
    
    @Schedule(second = "*/2", minute = "*", hour = "*")
    public void timerMethod() {
        ++t;
        s = t+" ";
        String m = "Message"+ s;
        try {
            sendJMSMessageToPostbox(m);
        } catch (JMSException ex) {
            Logger.getLogger(timerBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private Message createJMSMessageForjmsPostbox(Session session, Object messageData) throws JMSException {
        // TODO create and populate message to send
        TextMessage tm = session.createTextMessage();
        tm.setText(messageData.toString());
        return tm;
    }

    private void sendJMSMessageToPostbox(Object messageData) throws JMSException {
        Connection connection = null;
        Session session = null;
        try {
            connection = postboxFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(postbox);
            messageProducer.send(createJMSMessageForjmsPostbox(session, messageData));
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
                }
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
    
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
 
}
